import React, { Component } from 'react'
import {
  View,
  StyleSheet,
  Image,
  Text,
  ScrollView,
  TouchableOpacity,
  DeviceEventEmitter
} from 'react-native'
import AsyncStorage from '@react-native-community/async-storage';
import NavBar from '../../../../components/PublicHeader';
import getStorageValue from '../../../../utils/getStorageValue';
import fetchWebApi from '../../../../public/WebApi/fetchBase';
import Layer from '../../../../utils/Layer';
import Loading from '../../../../components/Loading';

import {
  GET_SELECTACCOUNT,
  POST_SWITCHACCOUNT
} from '../../../../public/WebApi/myInfoDataInterface/userInfoListApi';
import {
  POST_APPPOSITION_ADD
} from '../../../../public/WebApi/apiList';
import {
  Constant
} from '../../../../public/js/constant';
import {
  GetLocation
} from '../../../../utils/GetLocation'

export default class businLicense extends Component {
  constructor(props) {
    super(props)
    const {
      userType,
      defaultTrue,
      goBackTrue,
      typeUser,
      typeTrue,
      enterKey,
      key
    } = this.props.navigation.state.params
    this.state = {
      // 头部标题
      topTitle: "营业执照",
      // 认证类型
      authType: "",
      // 信用代码
      creditCode: "",
      // 营业执照图片
      filePath: null,
      // 公司名称
      name: "",
      defaultNum: null,
      // 判断是否为企业/个人
      userType: userType,
      defaultNumTrue: defaultTrue,
      goBackTrue: goBackTrue,
      key: key,
      typeTrue: typeTrue,
      typeUser: typeUser,
      enterKey: enterKey,

      longitude: 500,
      latitude: 500,
      positions: '',
    };
  }

  componentDidMount = () => {
    // 初始化 获取营业执照
    this.getBusinLicense()
    // 初始化地理定位 信息
    this.getUserLocaltion()

  }
  // 初始化地理定位
  async getUserLocaltion() {
    // Loading.show()
    await GetLocation();
    setTimeout(() => {
      if (Object.keys(GetLocation()._55).length > 0) {
        this.setState({
          latitude: GetLocation()._55.latitude,
          longitude: GetLocation()._55.longitude,
          positions: GetLocation()._55.positions.aois[0].name
        })
      } else {
        alert("获取地址失败，请重新进入系统！")
      }
    }, 3000)
  }

  // 地理定位 请求
  async position() {
    const {
      latitude,
      longitude,
      positions
    } = this.state
    if (latitude == 500 &&
      longitude == 500) {
      return;
    } else {
      const res = await fetchWebApi(POST_APPPOSITION_ADD,
        {
          token: await getStorageValue(Constant.TOKEN),
          flag: "1",
          lat: latitude,
          lon: longitude,
          placeName: positions
        }, 'POST');
      if (res.status == 200) {
      } else {
        Layer.showMsg(res.msg);
      }
    }
  }

  // 获取营业执照
  async getBusinLicense() {
    const res = await fetchWebApi(GET_SELECTACCOUNT,
      {
        token: await getStorageValue(Constant.TOKEN)
      }, 'POST');
    if (res.data) {
      if (res.status == 200) {
        const {
          authType,
          creditCode,
          filePath,
          name
        } = res.data
        this.setState({
          authType: authType,
          creditCode: creditCode,
          filePath: filePath,
          name: name
        })
      } else {
        Layer.showMsg("获取营业执照失败");
        return
      }
    } else {
      Layer.showMsg("您未认证营业执照");
      this.setState({
        defaultNum: true
      })
      return
    }

  }
  // 账号切换
  async postSwitchAccount() {
    const res = await fetchWebApi(POST_SWITCHACCOUNT,
      {
        token: await getStorageValue(Constant.TOKEN)
      }, 'POST');
    // 切换账户判断逻辑
    this.switchAccountFN(res)
  }

  // 切换账户判断逻辑
  async switchAccountFN(res) {
    const {
      typeTrue,
      defaultNumTrue,
    } = this.state
    if (res.status == 200) {
      await AsyncStorage.removeItem(Constant.TOKEN);
      if (
        defaultNumTrue ||
        typeTrue
      ) {
        await AsyncStorage.setItem(
          Constant.TOKEN,
          res.data.token
        );
        // 数据刷新判断
        this.userMaillistFN()

      }
    } else {
      Layer.showMsg("切换失败");
    }
  }

  // 数据刷新判断
  userMaillistFN() {
    const {
      enterKey,
      typeTrue
    } = this.state
    // 监听数据刷新
    const getUserMaillist = DeviceEventEmitter.emit(
      'getUserMaillist',
      true
    );
    if (typeTrue) {
      this.props.navigation.goBack(enterKey)
      getUserMaillist
    } else {
      this.props.navigation.goBack()
      this.props.navigation.state.params.getUserMaillistFN()
    }
    // 地理定位
    this.position()
  }

  // 企业账号修改
  businLicense() {
    const {
      authType,
      creditCode,
      filePath,
      name
    } = this.state
    this.props.navigation.navigate('enterAccount',
      {
        authType: authType,
        creditCode: creditCode,
        filePath: filePath,
        name: name,
        defaultBol: true,
        getBusinLicenseFN: () => {
          this.getBusinLicense()
        }
      })
  }
  render() {
    const {
      filePath,
      name,
      creditCode,
      authType,
      defaultNum,
      topTitle,
      userType,
      defaultNumTrue,
      goBackTrue,
      key
    } = this.state
    return (
      <View style={styles.warper}>
        {/* 导航栏 */}
        <Loading />
        <NavBar
          navigation={this.props.navigation}
          title={topTitle}
          titleColor={"#333"}
          right={defaultNum || goBackTrue ?
            "" : "修改"}
          pressRight={() => {
            defaultNum || goBackTrue ?
              null : this.businLicense()
          }}
          goBackTrue={goBackTrue}
          enterKey={key}
        />
        <ScrollView style={styles.warScrollView}>
          <View style={styles.businLicenseWAR}>
            <Text style={styles.businLicenseText}>请拍摄并上传你的营业执照</Text>
            <View>
              {filePath ?
                <TouchableOpacity onPress={() => {
                  this.props.navigation.push('friendAvatar',
                    {
                      friendAvatar: [{ url: filePath }],
                      defaultTrue: true
                    })
                }} style={styles.headPortrait}>
                  <Image style={styles.businLicenseIMG}
                    source={{ uri: filePath }} />
                </TouchableOpacity> :
                <View style={styles.businLicenseBoxI}>
                  <Text style={styles.filePathImg}>暂无营业执照</Text>
                </View>}
            </View>
            <View style={styles.businLicenseBox}>
              <Text style={styles.businLicenseText}>企业注册名称</Text>
              <View style={styles.itemBox}>
                <Text style={styles.textColor}>
                  {name ? name : "企业注册名称"}
                </Text>
              </View>
            </View>
            <View style={styles.businLicenseBox}>
              <Text style={styles.businLicenseText}>统一社会信用代码</Text>
              <View style={styles.itemBox}>
                <Text style={styles.textColor}>
                  {creditCode ? creditCode : "统一社会信用代码"}
                </Text>
              </View>
            </View>
            <View style={styles.businLicenseBox}>
              <Text style={styles.businLicenseText}>认证类型</Text>
              <View style={styles.itemBox}>
                <Text style={styles.textColor}>
                  {authType ? authType : "认证类型"}
                </Text>
              </View>
            </View>
          </View>
        </ScrollView >
        {
          userType == 0 &&
            defaultNumTrue == true ?
            <TouchableOpacity style={styles.enterAccountContainer}
              onPress={() => {
                this.postSwitchAccount()
              }}>
              <View style={styles.enterAccountBtn}>
                <Text style={styles.text}>切换企业账户</Text>
              </View>
            </TouchableOpacity>
            : null
        }
        {
          goBackTrue == false ?
            <TouchableOpacity style={styles.enterAccountContainer}
              onPress={() => {
                this.postSwitchAccount()
              }}>
              <View style={styles.enterAccountBtn}>
                <Text style={styles.text}>切换企业账户</Text>
              </View>
            </TouchableOpacity>
            : null
        }
      </View >
    )
  }
}
const styles = StyleSheet.create({
  warper: {
    flex: 1,
    position: "relative",
    backgroundColor: "#fff"
  },
  warScrollView: {
    // marginBottom: 80
  },
  businLicenseWAR: {
    paddingTop: 15,
    paddingLeft: 15,
    paddingRight: 15,
  },
  businLicenseText: {
    color: "#333",
    fontSize: 18,
    marginBottom: 20
  },
  businLicenseIMG: {
    width: "100%",
    height: 244,
    borderRadius: 6,
  },
  businLicenseBoxI: {
    justifyContent: "center",
    alignItems: "center",
    width: "100%",
    height: 244,
    borderRadius: 6,
    backgroundColor: "#f5f5f5"
  },
  filePathImg: {
    color: "#333",
    fontSize: 16
  },
  businLicenseBox: {
    marginTop: 20
  },
  itemBox: {
    width: "100%",
    height: 50,
    paddingLeft: 15,
    borderRadius: 6,
    justifyContent: "center",
    backgroundColor: "#f5f5f5"
  },
  textColor: {
    fontSize: 16,
    color: "#333",
  },
  enterAccountContainer: {
    position: "absolute",
    bottom: 10,
    width: "100%",
    height: 40,
    paddingLeft: 15,
    paddingRight: 15,
    justifyContent: "center",
    alignItems: "center",
  },
  enterAccountBtn: {
    width: "100%",
    height: 40,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 50,
    backgroundColor: "#1890FF"
  },
  text: {
    color: "#fff",
    fontSize: 18
  },

})